<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfos.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="showDialog">添加</el-button>
        </el-col>
      </el-row>

      <!-- 列表 -->
      <el-table
        :data="userList"
        border
        stripe
        style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="create_time"
          label="日期"
          width="180">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态">
          <template slot-scope="scope">
            <el-switch
            v-model="scope.row.mg_state"
            @change="userStateChanged(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          width="180px"
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfos.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfos.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用戶"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeDialog">
      <el-form ref="addUserRef" :model="addUser" :rules="addUserRules" label-width="80px">
        <el-form-item label="用戶名称" prop="username">
          <el-input v-model="addUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密碼" prop="password">
          <el-input v-model="addUser.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="手機號" prop="mobile">
          <el-input v-model="addUser.mobile" maxLength="11"></el-input>
        </el-form-item>
        <el-form-item label="郵箱" prop="email">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用戶信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeEditDialog"
    ><span>{{editUserInfo.mobile}}</span>
      <el-form :model="editUserInfo" :rules="editUserInfoRules" ref="editUserInfoRef" label-width="100px">
        <el-form-item label="用户名称">
          <el-input v-model="editUserInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserInfo.mobile" maxLength="11"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserInfo.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="reviseUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 校驗郵箱規則
    var checkEmail = (rule, value, callback) => {
      // eslint-disable-next-line no-useless-escape
      var regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error("郵箱有誤！"))
    }
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error("請輸入合法手機號"))
    }
    return {
      queryInfos: {
        query: '',
        pagenum: 1,
        pagesize: 1
      },
      userList: [],
      pageTotal: 0,
      dialogVisible: false, // 顯示對話框
      addUser: { // 添加用戶信息表單
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      addUserRules: { // 添加用戶表單校驗規則
        username: [
          { required: true, message: '请输入用戶名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密碼', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手機號', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入郵箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      editDialogVisible: false, // 显示修改用戶信息对话框
      editUserInfo: {}, // 当前修改的用户信息
      editUserInfoRules: {
        mobile: [
          { required: true, message: '请输入手机号--000', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入郵箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfos })
      this.userList = res.data.users
      this.pageTotal = res.data.total
    },
    // 每页多少条
    handleSizeChange(a) {
      this.queryInfos.pagesize = a
      this.getUserList()
    },
    // 当前第几页
    handleCurrentChange(p) {
      this.queryInfos.pagenum = p
      this.getUserList()
      // console.log(p)
    },
    // 用户状态发生变化
    async userStateChanged(userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error("用户状态更新失败！")
      }
      this.$message.success("用户状态更新成功！")
    },
    // 顯示添加用戶對話框
    showDialog() {
      this.dialogVisible = true
    },
    // 關閉對話框
    closeDialog() {
      // 重置表单信息
      this.$refs.addUserRef.resetFields()
    },
    // 添加用户信息接口
    addUserBtn() {
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) return this.$message.error("添加失败")
        const { data: res } = await this.$http.post('users', this.addUser)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.userList.unshift(res.data)
        this.dialogVisible = false
      })
    },
    // 修改用户信息
    edit(currentUser) {
      this.editDialogVisible = true
      this.editUserInfo = currentUser
      // Object.assign(this.editUserInfo, currentUser)
    },
    // 确定修改用户信息
    reviseUserInfo() {
      this.$refs.editUserInfoRef.validate(async (valid) => {
        if (!valid) return
        console.log(this.editUserInfo, valid)
        const { data: res } = await this.$http.put(`users/${this.editUserInfo.id}`, this.editUserInfo)
        if (res.meta.status !== 200) {
          return this.$message.error("更新失败")
        } else {
          this.$message.success("更新成功")
          this.getUserList()
        }
        console.log(res)
        this.editDialogVisible = false
      })
    },
    // 关闭修改用户信息对话框
    closeEditDialog() {
      this.$refs.editUserInfoRef.resetFields()
    },
    // 删除当前用户
    async removeUser(userinfo) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') { // 确定删除
          return this.$message('取消删除')
        }
        const { data: res } = await this.$http.delete(`users/${userinfo.id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除用户成功')
        this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-table,
.el-pagination {
  margin-top: 15px !important;
}
</style>
